package com.example.safeassistan.train.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.viewpager.widget.ViewPager;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.train.fragment.ProblemSimulateJudgeFragment;
import com.example.safeassistan.train.fragment.ProblemSimulateMutliFragment;
import com.example.safeassistan.train.fragment.ProblemSimulateSingleFragment;
import com.example.safeassistan.train.model.SimulateAnswerProblemModel;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.widget.ExitAnswerProblemDialog;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ActivitySimulateAnswerProblem extends BaseActivity implements View.OnClickListener {
    private ImageView _barIvRight;
    private ImageView _barBack;

    private TextView tvProcess,_barTitle;
    private List<Fragment> fragments;
    private String paperId="";
    private SimulateAnswerProblemModel model;
    private ViewPager viewPager;
    private MainAdapter mainAdapter;
    private CountDownTimer timer=null;

    private List<List<String>> options;//总列表
    private List<String> singleoption;//单选
    private List<String> multioption;//多选
    private List<String> judgeoption;//判断


    private List<List<String>> myOptions;//总列表
    private List<String> mysingleoption;//单选
    private List<String> myMultioption;//多选
    private List<String> myjudgeoption;//判断
    private int time=0;//考试总时间  分钟
    private int totalCount=0;//总试题数目
    private int cuttrenPosi=0;//当前答题位置
    private String startTime="";//开始时间
    private String surplusTime="";//剩余时间


    public static void actionStart(Context context,String paperId,String time) {
        Intent intent = new Intent(context, ActivitySimulateAnswerProblem.class);
        intent.putExtra("paperId",paperId);
        intent.putExtra("time",time);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id._barIvRight:
                //答题卡
                options.clear();
                myOptions.clear();
                options.add(singleoption);
                options.add(multioption);
                options.add(judgeoption);

                myOptions.add(mysingleoption);
                myOptions.add(myMultioption);
                myOptions.add(myjudgeoption);

                ActivitySimulateAnswerCard.actionStart(getContext(),options,myOptions,paperId,
                        model.getResult().getPaperMark1()==null?0:model.getResult().getPaperMark1(),
                        model.getResult().getPaperMark2()==null?0:model.getResult().getPaperMark2(),
                        model.getResult().getPaperMark3()==null?0:model.getResult().getPaperMark3(),startTime,surplusTime );
                break;
            case R.id._barBack:
                //退出按钮
                cuttrenPosi=0;
                circleFun();
                ExitAnswerProblemDialog dialog=new ExitAnswerProblemDialog(getContext(),totalCount,cuttrenPosi, totalCount-cuttrenPosi);
                dialog.setClicklistener(new ExitAnswerProblemDialog.ClickListenerInterface() {
                    @Override
                    public void doExit() {
                        dialog.dismiss();
                        finish();
                    }
                });
                dialog.show();
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_similate_answer_problem;
    }

    @Override
    protected void initView() {
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.safeassistan.ActivitySimulateAnswerProblem");
        lbm.registerReceiver(mMessageReceiver, filter);
        paperId=getIntent().getStringExtra("paperId");
        time=Integer.parseInt(getIntent().getStringExtra("time"));
        _barIvRight=findViewById(R.id._barIvRight);
        _barTitle=findViewById(R.id._barTitle);
        _barIvRight.setImageResource(R.mipmap.icon_test_answer_card);
        _barIvRight.setVisibility(View.VISIBLE);
        _barIvRight.setOnClickListener(this::onClick);
        _barBack=findViewById(R.id._barBack);
        _barBack.setOnClickListener(this::onClick);
        tvProcess=findViewById(R.id.tvProcess);
        viewPager=findViewById(R.id.viewPager);
        options=new ArrayList<>();
        myOptions=new ArrayList<>();
        fragments=new ArrayList<>();
        getData();
    }

    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            cuttrenPosi=0;
            circleFun();
                ExitAnswerProblemDialog dialog=new ExitAnswerProblemDialog(getContext(),totalCount,cuttrenPosi, totalCount-cuttrenPosi);
                dialog.setClicklistener(new ExitAnswerProblemDialog.ClickListenerInterface() {
                    @Override
                    public void doExit() {
                        dialog.dismiss();
                        finish();
                    }
                });
                dialog.show();
        }
        return false;
    }

    public void getData(){
        new HttpRequest(this).doGet(UrlConstants.testAnswer+paperId, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    int code = jsonObject.getInt("code");
                    if (code == 200) {
                        Object obj = JsonUtils.fromJson(result.toString(), SimulateAnswerProblemModel.class);
                        if (obj instanceof SimulateAnswerProblemModel) {
                            model=(SimulateAnswerProblemModel) obj;
                            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            startTime=sf.format(System.currentTimeMillis());

                            totalCount=model.getResult().getJudgeList().size()+model.getResult().getManyList().size()+model.getResult().getSingleList().size();

                            singleoption= Arrays.asList(new String[model.getResult().getSingleList().size()]);
                            multioption=Arrays.asList(new String[model.getResult().getManyList().size()]);
                            judgeoption=Arrays.asList(new String[model.getResult().getJudgeList().size()]);

                            mysingleoption= Arrays.asList(new String[model.getResult().getSingleList().size()]);
                            myMultioption=Arrays.asList(new String[model.getResult().getManyList().size()]);
                            myjudgeoption=Arrays.asList(new String[model.getResult().getJudgeList().size()]);

                            for (int i=0;i<model.getResult().getSingleList().size();i++){
                                fragments.add(ProblemSimulateSingleFragment.newInstance(i+1,i,model.getResult().getSingleList().get(i)));
                            }

                            for (int i=0;i<model.getResult().getManyList().size();i++){
                                fragments.add(ProblemSimulateMutliFragment.newInstance(fragments.size(),i,model.getResult().getManyList().get(i)));
                            }
                            for (int i=0;i<model.getResult().getJudgeList().size();i++){
                                fragments.add(ProblemSimulateJudgeFragment.newInstance(fragments.size(),i,model.getResult().getJudgeList().get(i)));

                            }
                            mainAdapter=new MainAdapter(getSupportFragmentManager());
                            viewPager.setAdapter(mainAdapter);
                            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                                }

                                @Override
                                public void onPageSelected(int position) {
                                    tvProcess.setText((position+1)+"/"+fragments.size());
                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                            });
                            tvProcess.setText("1/"+fragments.size());
                            timer=new CountDownTimer(time*60*1000,1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    surplusTime=formatTime(time*60*1000-millisUntilFinished);
                                    _barTitle.setText(formatTime(millisUntilFinished));
                                }

                                @Override
                                public void onFinish() {
                                    //当倒计时结束需要考生提交考卷
                                    Toast.makeText(getContext(),"您好，考试已经结束，请停止答题",Toast.LENGTH_SHORT).show();
                                    options.clear();
                                    myOptions.clear();
                                    options.add(singleoption);
                                    options.add(multioption);
                                    options.add(judgeoption);

                                    myOptions.add(mysingleoption);
                                    myOptions.add(myMultioption);
                                    myOptions.add(myjudgeoption);

                                    ActivitySimulateAnswerCard.actionStart(getContext(),options,myOptions,paperId,
                                            model.getResult().getPaperMark1(),
                                            model.getResult().getPaperMark2(),
                                            model.getResult().getPaperMark3(),startTime,surplusTime);
                                }
                            };
                            timer.start();
                        }
                    }else {
                        Toast.makeText(ActivitySimulateAnswerProblem.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    /**
     * 将毫秒转化为 分钟：秒 的格式
     * @param millisecond 毫秒
     */
    public String formatTime(long millisecond) {
        int minute;//分钟
        int second;//秒数
        int hour;//小时
        minute = (int) ((millisecond / 1000) / 60 % 60);
        second = (int) ((millisecond / 1000) % 60);
        hour = (int) ((millisecond / 1000) / 60 / 60);
        if (hour < 10) {
            if (minute < 10) {
                if (second < 10) {
                    return "0" + hour + ":" + "0" + minute + ":" + "0" + second;
                } else {
                    return "0" + hour + ":" + "0" + minute + ":" + second;
                }
            } else {
                if (second < 10) {
                    return "0" + hour + ":" + minute + ":" + "0" + second;
                } else {
                    return "0" + hour + ":" + minute + ":" + second;
                }
            }
        } else {
            if (minute < 10) {
                if (second < 10) {
                    return  hour + ":" + "0" + minute + ":" + "0" + second;
                } else {
                    return  hour + ":" + "0" + minute + ":" + second;
                }
            } else {
                if (second < 10) {
                    return hour + ":" + minute + ":" + "0" + second;
                } else {
                    return  hour + ":" + minute + ":" + second;
                }
            }
        }
    }

    //适配器
    public class MainAdapter extends FragmentPagerAdapter {

        public MainAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        //获取标题
        @Override
        public CharSequence getPageTitle(int position) {
            return "";
        }
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.example.safeassistan.ActivitySimulateAnswerProblem")) {
                if (intent.getIntExtra("type",-1)!=-1){
                    switch (intent.getIntExtra("type",-1)){
                        case 1:
                            //单选
                            singleoption.set(intent.getIntExtra("posi",0),intent.getStringExtra("result"));
                            mysingleoption.set(intent.getIntExtra("posi",0),intent.getStringExtra("option"));
                            break;
                        case 2:
                            //多选
                            multioption.set(intent.getIntExtra("posi",0),intent.getStringExtra("result"));
                            myMultioption.set(intent.getIntExtra("posi",0),intent.getStringExtra("option"));
                            break;
                        case 3:
                            //判断
                            judgeoption.set(intent.getIntExtra("posi",0),intent.getStringExtra("result"));
                            myjudgeoption.set(intent.getIntExtra("posi",0),intent.getStringExtra("option"));
                            break;
                    }
                }
            }
        }
    };


    //循环遍历判断已做题目数
    public void circleFun(){
        //遍历有多少题做了有多少题没有做
        for (int i=0;i<singleoption.size();i++){
            if (singleoption.get(i)!=null&&!singleoption.get(i).equals("")){
                cuttrenPosi++;
            }
        }
        for (int i=0;i<multioption.size();i++){
            if (multioption.get(i)!=null&&!multioption.get(i).equals("")){
                cuttrenPosi++;
            }
        }
        for (int i=0;i<judgeoption.size();i++){
            if (judgeoption.get(i)!=null&&!judgeoption.get(i).equals("")){
                cuttrenPosi++;
            }
        }
    }



    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    @Override
    public void onAttachFragment(@NonNull Fragment fragment) {
        super.onAttachFragment(fragment);
    }
}
